package com.ruoyi.system.controller;

import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.PreAuthorize;
import com.ruoyi.system.domain.SysBmType;
import com.ruoyi.system.domain.vo.SysBmGoodsExcelVO;
import com.ruoyi.system.service.ISysBmGoodsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 编码配置Controller
 *
 * @author yy
 * @date 2021-11-19
 */
@Api(tags = " 物资编码配置")
@RestController
@RequestMapping("/sysBmGoods")
public class SysBmGoodsController extends BaseController {
    @Autowired
    private ISysBmGoodsService sysBmGoodsService;

    /**
     * 查询编码配置列表
     */
    @ApiOperation(value = "查询编码配置列表", notes = "查询编码配置列表")
    @PreAuthorize(hasPermi = "sysBmType:sysBmType:list")
    @GetMapping("/list")
    public AjaxResult list(SysBmType sysBmType) {
        List<SysBmType> list = sysBmGoodsService.selectSysBmTypeList(sysBmType);
        return AjaxResult.success(list);
    }

    @ApiOperation(value = "远程查询编码配置接口", notes = "远程查询编码配置接口")
    @PostMapping("/query")
    public List<SysBmType> query(@RequestBody SysBmType sysBmType) {
        List<SysBmType> list = sysBmGoodsService.selectSysBmTypeList(sysBmType);
        return list;
    }

    /**
     * 导出编码配置列表
     */
    @ApiOperation(value = "导出编码配置列表", notes = "导出编码配置列表")
    @PreAuthorize(hasPermi = "sysBmType:sysBmType:export")
    @Log(title = "编码配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysBmType sysBmType) throws IOException {
        List<SysBmType> list = sysBmGoodsService.selectSysBmTypeList(sysBmType);
        ExcelUtil<SysBmType> util = new ExcelUtil<SysBmType>(SysBmType.class);
        util.exportExcel(response, list, "编码配置数据");
    }

    /**
     * 获取编码配置详细信息
     */
    @ApiOperation(value = "获取编码配置详细信息", notes = "获取编码配置详细信息")
    @PreAuthorize(hasPermi = "sysBmType:sysBmType:query")
    @GetMapping(value = "/{bmId}")
    public AjaxResult getInfo(@PathVariable("bmId") Long bmId) {
        return AjaxResult.success(sysBmGoodsService.selectSysBmTypeById(bmId));
    }

    /**
     * 新增编码配置
     */
    @ApiOperation(value = "新增编码配置", notes = "新增编码配置")
    @PreAuthorize(hasPermi = "sysBmType:sysBmType:add")
    @Log(title = "编码配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysBmType sysBmType) {
        return toAjax(sysBmGoodsService.insertSysBmType(sysBmType));
    }

    /**
     * 修改编码配置
     */
    @ApiOperation(value = "修改编码配置", notes = "修改编码配置")
    @PreAuthorize(hasPermi = "sysBmType:sysBmType:edit")
    @Log(title = "编码配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody List<SysBmType> sysBmTypes) {
        for (SysBmType sysBmType : sysBmTypes) {
            sysBmGoodsService.updateSysBmType(sysBmType);
        }
        return AjaxResult.success("修改成功");
    }

    /**
     * 删除编码配置
     */
    @ApiOperation(value = "删除编码配置", notes = "删除编码配置")
    @ApiImplicitParam(name = "ids", value = "编码配置ID数组", required = true, paramType = "path", allowMultiple = true, dataType = "String")
    @PreAuthorize(hasPermi = "sysBmType:sysBmType:remove")
    @Log(title = "编码配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{bmIds}")
    public AjaxResult remove(@PathVariable Long[] bmIds) {
        return toAjax(sysBmGoodsService.deleteSysBmTypeByIds(bmIds));
    }


    /**
     * 导入物料编码记录列表,
     */
    @ApiOperation(value = "导入物料编码记录列表", notes = "导入物料编码记录列表")
    @PreAuthorize(hasPermi = "sysBmType:sysBmType:import")
    @Log(title = "导入物料编码记录列表", businessType = BusinessType.IMPORT)
    @RequestMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {

        ExcelUtil<SysBmGoodsExcelVO> util = new ExcelUtil<SysBmGoodsExcelVO>(SysBmGoodsExcelVO.class);
        List<SysBmGoodsExcelVO> sysBmGoodsExcelVOS = util.importExcel(file.getInputStream());
        //批量插入数据
        sysBmGoodsExcelVOS = sysBmGoodsExcelVOS.stream().filter(o -> StringUtils.isNotBlank(o.getLevelCode())).collect(Collectors.toList());

        Map<String, List<SysBmGoodsExcelVO>> listMap = sysBmGoodsExcelVOS.stream().collect(Collectors.groupingBy(SysBmGoodsExcelVO::getLevelName));


        for (Map.Entry<String, List<SysBmGoodsExcelVO>> entry : listMap.entrySet()) {
            // 判断一级是否存在
            String levelName = entry.getKey();
            String levelCode = entry.getValue().get(0).getLevelCode();
            SysBmType q1 = new SysBmType();
            q1.setName(levelName);
            q1.setValue(levelCode);
            q1.setParentId(0L);
            List<SysBmType> l1 = sysBmGoodsService.selectSysBmTypeList(q1);
            Long parentId = 0L;
            if (l1.size() == 0) {
                q1.setLv(1);
                q1.setCode("1");
                q1.setParentId(0L);
                q1.setGenCode(levelCode);
                q1.setHierarchy(levelName);
                sysBmGoodsService.insertSysBmType(q1);
                parentId = q1.getBmId();
            }
            Map<String, List<SysBmGoodsExcelVO>> deviceSystem = entry.getValue().stream().collect(Collectors.groupingBy(SysBmGoodsExcelVO::getTypeName));

            for (Map.Entry<String, List<SysBmGoodsExcelVO>> systemEntry : deviceSystem.entrySet()) {
                String typeName = systemEntry.getKey();
                String typeCode = systemEntry.getValue().get(0).getTypeCode();
                SysBmType q2 = new SysBmType();
                q2.setName(typeName);
                q2.setValue(typeCode);
                q2.setParentId(parentId);
                List<SysBmType> l2 = sysBmGoodsService.selectSysBmTypeList(q2);
                long deviceSystemParent = 0L;
                if (l2.size() == 0) {
                    q2.setLv(2);
                    q2.setCode("0");
                    q2.setParentId(parentId);
                    q2.setGenCode(levelCode + "-" + typeCode);
                    q2.setHierarchy(levelName + "-" + typeName);
                    sysBmGoodsService.insertSysBmType(q2);
                    deviceSystemParent = q2.getBmId();
                }
            }
        }

        return AjaxResult.success();

    }


}
